package com.topsun.framework.common.core.util;

import cn.hutool.core.util.ObjectUtil;
import com.topsun.framework.common.core.constants.CoreConstants;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * @Package cloud.chenglang.data.web.util
 * @author: 皮皮
 * @date: 2021/3/23 4:43 PM
 */
@Slf4j
public class RequestUtil {


    public static synchronized String requestId() {
        String requestId = getRequestId();
        if (ObjectUtil.isNull(requestId)) {
            requestId = IdUtil.getInstance().getIdStr();
            MDC.put(CoreConstants.REQUEST_ID_MDC_KEY, requestId);
        }
        return requestId;
    }

    public static String getRequestId() {
        return MDC.get(CoreConstants.REQUEST_ID_MDC_KEY);
    }

    /**
     * 获取请求来源的IP,可以适应前置部署有Nginx等反向代理软件等的情况. HTTP_CLIENT_IP 无法伪造，所以放在第一个
     * http://blog.csdn.net/songylwq/article/details/7701718
     *
     * @param request
     * @return
     * @author Stone
     */
    public static String getRequestSourceIp(HttpServletRequest request) {
        String ip = request.getHeader("HTTP_CLIENT_IP");

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_FORWARDED");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-FORWARDED-FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        log.debug(ip);

        if (ip != null && ip.length() > 0) {
            ip = ip.replaceAll("0:0:0:0:0:0:0:1", "127.0.0.1");
            // 以下逻辑处理nginx多级代理
            String[] split = ip.split(",");
            if (split.length > 1) {
                for (int i = split.length - 1; i >= 0; i--) {
                    ip = split[i].trim();
                    if (!Objects.equals(ip, "127.0.0.1")) {
                        break;
                    }
                }
            }
        }
        return ip;
    }
}
